package com.wondream.myframework.spring.proxy;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

public class CglibProxy implements MethodInterceptor {
    private Object target;

    public CglibProxy() {
    }

    public CglibProxy(Object target) {
        this.target = target;
    }

    public Object createProxy(){
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(target.getClass());
        enhancer.setCallback(this);
        return enhancer.create();
    }

    @Override
    public Object intercept(Object o, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
        System.out.println("invoke before");
        method.invoke(target, args);
        System.out.println("invoke after");
        return null;
    }

    public static void main(String[] args) {
        Girl girl = new Girl();
        Girl proxy = (Girl)new CglibProxy(girl).createProxy();
        proxy.eat();
        proxy.bath();
    }
}
